package io.renren.modules.archive.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.file.FileTypeUtils;
import io.renren.common.file.FileUploadUtils;
import io.renren.common.file.FileUtils;
import io.renren.common.utils.*;
import io.renren.modules.archive.service.ArchiveAttachService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.ofdrw.converter.ConvertHelper;

import org.ofdrw.reader.ContentExtractor;
import org.ofdrw.reader.OFDReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.archive.entity.ArchiveAttachEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 档案附件表
 *
 * @author yuancc
 * @email 1015572358@qq.com
 * @date 2023-07-27 15:37:16
 */
@RestController
@RequestMapping("archive/archiveattach")
public class ArchiveAttachController {
    @Autowired
    private ArchiveAttachService archiveAttachService;

    /**
     * 列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("archive:archiveattach:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = archiveAttachService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{attachId}")
//    @RequiresPermissions("archive:archiveattach:info")
    public R info(@PathVariable("attachId") Long attachId) {
        ArchiveAttachEntity archiveAttach = archiveAttachService.getById(attachId);

        return R.ok().put("archiveAttach", archiveAttach);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
//    @RequiresPermissions("archive:archiveattach:save")
    public R save(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = ConfigConstant.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);

            //插入数据库操作
            ArchiveAttachEntity archiveAttachEntity = new ArchiveAttachEntity();
            archiveAttachEntity.setFileName(FileUtils.getNameNotSuffix(file.getOriginalFilename()));
            long v = file.getSize() / 1024;
            archiveAttachEntity.setFileSize(v);
            archiveAttachEntity.setFileDate(new Date());
            archiveAttachEntity.setExt(FileTypeUtils.getMultiFileType(file));
            archiveAttachEntity.setPath(fileName);
            archiveAttachEntity.setServer("server");
//            archiveAttachEntity.setContent(fileContent);
            archiveAttachService.save(archiveAttachEntity);
            R ajax = R.ok();
            ajax.put("url", fileName);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            ajax.put("attachId",archiveAttachEntity.getAttachId());
            return ajax;
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("archive:archiveattach:update")
    public R update(@RequestBody ArchiveAttachEntity archiveAttach) {
        archiveAttachService.updateById(archiveAttach);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
//    @RequiresPermissions("archive:archiveattach:delete")
    public R delete(@RequestBody Long[] attachIds) {
        archiveAttachService.removeByIds(Arrays.asList(attachIds));

        return R.ok();
    }

    /**
     * 删除附件
     */
    @RequestMapping("/delAttachFile")
//    @RequiresPermissions("archive:archiveattach:delete")
    public R delAttachFile(@RequestBody Long attachId) {
        if(attachId == null){
            throw new RRException("未获取到附件id");
        }
        archiveAttachService.removeById(attachId);

        return R.ok();
    }


    /**
     * 文档识别
     */
    @RequestMapping("/archiveIdentify")
//    @RequiresPermissions("archive:archiveattach:archiveIdentify")
    public R archiveIdentify(@RequestParam Map<String, Object> params) {
        String fileName = (String)params.get("fileName");

       List<ArchiveAttachEntity> list=archiveAttachService.queryListByName(fileName);

        String path=list.get(0).getPath();
        String fileContent="";
        if(path.endsWith(".pdf")||path.endsWith(".png")||path.endsWith(".jpg")){

            fileContent= OCRUtils.identify(path);

        }else if(path.endsWith(".ofd")){
            OFDReader reader = null;
            try {
                //读ofd文件
                reader = new OFDReader(path);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //提取文字
            ContentExtractor extractor = new ContentExtractor(reader);

            List<String> pageContent = extractor.extractAll();
            StringBuffer stringBuffer = new StringBuffer();
            //循环提取
            for (String s : pageContent) {
                stringBuffer.append(s);
            }
            fileContent=stringBuffer.toString();
        }else{
            return R.error();
        }

        UpdateWrapper<ArchiveAttachEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("attach_id", list.get(0).getAttachId()).set("content", fileContent);
        archiveAttachService.update(updateWrapper);

        return R.ok().put("content",fileContent);
    }


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     *
     */
    @GetMapping("/download")
    public void fileDownload(String fileName,  HttpServletResponse response, HttpServletRequest request) {
         List<ArchiveAttachEntity> archiveList=  archiveAttachService.queryListByName(fileName);
         if(archiveList.size()>0){
             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
             try {
                 String encodedFileName = URLEncoder.encode(fileName, "UTF-8"); // 对文件名进行 URL 编码
                 String lastName=archiveList.get(0).getPath().substring(archiveList.get(0).getPath().lastIndexOf("."));

                 FileUtils.setAttachmentResponseHeader(response, encodedFileName + lastName);
             } catch (UnsupportedEncodingException e) {
                 e.printStackTrace();
             }
             try {
                 FileUtils.writeBytes(archiveList.get(0).getPath(), response.getOutputStream());
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }

         }



    /**
     * 通用下载请求
     *
     * @param path 文件名称
     *
     */
    @GetMapping("/downloadByPath")
    public void fileDownloadByPath(String fileName,String path,  HttpServletResponse response, HttpServletRequest request) {

        if(!fileName.equals("")&&!path.equals("")){
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            try {
                String encodedFileName = URLEncoder.encode(fileName, "UTF-8"); // 对文件名进行 URL 编码
                String lastName=path.substring(path.lastIndexOf("."));

                FileUtils.setAttachmentResponseHeader(response, encodedFileName + lastName);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            try {
                FileUtils.writeBytes(path, response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


         }
